#!/bin/bash

ACTION=$1
shift

mkdir -p /storage/.config/distribution/configs/bluetooth/

# only start the bt agent if not already running 
NPID=$(pgrep -f batocera-bluetooth-agent)
if [[ -z "$NPID" ]]; then
 (systemd-run batocera-bluetooth-agent) || :
sleep 3
fi

do_help() {
    echo "${1} list" >&2
    echo "${1} trust" >&2
    echo "${1} remove <device address>" >&2
}


do_list() {
    find /storage/.cache/bluetooth -type f -name info |
	while read FILE
	do
	    if grep -qE '^Trusted=true$' "${FILE}"
	    then
		DEVNAME=$(grep -E '^Name=' "${FILE}" | sed -e s+"^Name="++)
		DEVADDR=$(basename $(dirname "${FILE}"))
		echo "${DEVADDR} ${DEVNAME}"
	    fi
	done
}

do_remove() {
    DEV="${1}"

    # output is never nice
    if ! (echo "untrust ${DEV}" ; echo "remove ${DEV}") | bluetoothctl >/dev/null 2>/dev/null
    then
	return 1
    fi
  
    return 0
}

do_trust() {
	NPID=$(pgrep -f batocera-bluetooth-agent)
    test -z "${NPID}" && return 0

    touch "/var/run/bt_status" || retrun 1
    LAST_MSG=$(cat "/var/run/bt_status")
    
    # start discovering
    kill -10 "${NPID}"

    trap "kill -12 ${NPID}" 2 3

    N=30
    while test $N -gt 0
    do
	NEW_MSG=$(cat "/var/run/bt_status")
	if test "${LAST_MSG}" != "${NEW_MSG}"
	then
	    LAST_MSG="${NEW_MSG}"
	    echo "${NEW_MSG}"
	fi
	sleep 1
	let N--
    done

    # stop discovering
    kill -12 "${NPID}"
 
}

do_starttrust() {
	NPID=$(pgrep -f batocera-bluetooth-agent)
    test -z "${NPID}" && exit 0

    # start discovering
    kill -10 "${NPID}"
}

do_stoptrust() {
	NPID=$(pgrep -f batocera-bluetooth-agent)
    test -z "${NPID}" && exit 0

    # stop discovering
    kill -12 "${NPID}"
}

case "${ACTION}" in
    "list")
	do_list
	;;
    "trust")
	do_trust
	;;
    "starttrust")
	do_starttrust
	;;
    "stoptrust")
	do_stoptrust
	;;
    "remove")
	if test $# = 1
	then
	    do_remove "${1}" || exit 1
	else
	    do_help "${0}"
	    exit 1
	fi
	;;
    *)
	do_help "${0}"
	exit 1
esac

exit 0
